import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken,removeToken } from '@/utils/auth';
import { isRelogin } from '@/utils/request';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';

NProgress.configure({ showSpinner: false });

/* const whiteList = [
	'/login', 
	'/home',
	'/list',
	'/search', 
	'/course', 
	'/pay',
	'/pay/success', 
	'/bind', 
	'/register', 
	'/player', 
	'/list', 
	'/search', 
	'/profile', 
	'/profile', 
	'/profile/course', 
	'/profile/order', 
	'/profile/collect', 
	'/profile/set', 
	'/profile/note'
]; */
const whiteList = [
	'/login', 
	'/home',
	'/list',
	'/search', 
	'/course',
	'/bind', 
	'/register', 
	'/list', 
	'/search',
];
router.beforeEach(async(to, from, next) => {
  const settingsStore = useSettingsStore()
  const userStore = useUserStore()
	NProgress.start();
	if (getToken()) {
		to.meta.title && settingsStore().setTitle(to.meta.title);
		/* has token*/
		if (to.path === '/login') {
			NProgress.done();
			next({ path: '/' });
		} else {
			let userInfo = userStore.user;
			if (userInfo) {
				next();
			} else {
				try {
					// get user info
					await userStore.getInfo();
					userInfo = userStore.user;
					if (userInfo) {
						next();
					} else {
						removeToken();
						next(`/login?redirect=${to.path}`);
						NProgress.done();
					}
				} catch (error) {
					// remove token and go to login page to re-login
					removeToken();
					next(`/login?redirect=${to.path}`);
					NProgress.done();
				}
			}
		}
	} else {
		// 没有token
		if (whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next();
		} else {
			next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
